package sdk

import (
	"context"
	"encoding/json"
	"fmt"
	"net/url"

	"github.com/yourusername/virt-manager-go/internal/models"
)

// ConnectionClient 提供连接管理相关的 API 操作
type ConnectionClient struct {
	client *APIClient
}

// NewConnectionClient 创建新的连接客户端
func NewConnectionClient(client *APIClient) *ConnectionClient {
	return &ConnectionClient{
		client: client,
	}
}

// ListConnections 列出所有连接
func (c *ConnectionClient) ListConnections(ctx context.Context) ([]models.ConnectionDetail, error) {
	data, err := c.client.Get(ctx, "/api/v1/connections")
	if err != nil {
		return nil, fmt.Errorf("failed to list connections: %w", err)
	}

	// API 返回的是包装格式 {"connections": [...], "count": n}
	var response struct {
		Connections []models.ConnectionDetail `json:"connections"`
		Count       int                       `json:"count"`
	}
	if err := json.Unmarshal(data, &response); err != nil {
		return nil, fmt.Errorf("failed to unmarshal connections response: %w", err)
	}

	return response.Connections, nil
}

// GetConnection 获取连接详情
func (c *ConnectionClient) GetConnection(ctx context.Context, connectionID string) (*models.ConnectionDetail, error) {
	// 构建带查询参数的URL
	u := fmt.Sprintf("/api/v1/connection?connection=%s", url.QueryEscape(connectionID))

	data, err := c.client.Get(ctx, u)
	if err != nil {
		return nil, fmt.Errorf("failed to get connection: %w", err)
	}

	var connection models.ConnectionDetail
	if err := json.Unmarshal(data, &connection); err != nil {
		return nil, fmt.Errorf("failed to unmarshal connection: %w", err)
	}

	return &connection, nil
}

// CreateConnection 添加新连接
func (c *ConnectionClient) CreateConnection(ctx context.Context, req *models.CreateConnectionRequest) error {
	_, err := c.client.Post(ctx, "/api/v1/connections", req)
	if err != nil {
		return fmt.Errorf("failed to add connection: %w", err)
	}
	return nil
}

// DeleteConnection 删除连接
func (c *ConnectionClient) DeleteConnection(ctx context.Context, connectionID string) error {
	// 构建带查询参数的URL
	u := fmt.Sprintf("/api/v1/connection?connection=%s", url.QueryEscape(connectionID))

	_, err := c.client.Delete(ctx, u)
	if err != nil {
		return fmt.Errorf("failed to remove connection: %w", err)
	}
	return nil
}

// GetConnectionInfo 获取连接信息
func (c *ConnectionClient) GetConnectionInfo(ctx context.Context, connectionID string) (*models.ConnectionDetail, error) {
	// 构建带查询参数的URL
	u := fmt.Sprintf("/api/v1/connection/info?connection=%s", url.QueryEscape(connectionID))

	data, err := c.client.Get(ctx, u)
	if err != nil {
		return nil, fmt.Errorf("failed to get connection info: %w", err)
	}

	var connection models.ConnectionDetail
	if err := json.Unmarshal(data, &connection); err != nil {
		return nil, fmt.Errorf("failed to unmarshal connection info: %w", err)
	}

	return &connection, nil
}

// GetConnectionCapabilities 获取连接功能信息
func (c *ConnectionClient) GetConnectionCapabilities(ctx context.Context, connectionID string) (string, error) {
	// 构建带查询参数的URL
	u := fmt.Sprintf("/api/v1/connection/capabilities?connection=%s", url.QueryEscape(connectionID))

	data, err := c.client.Get(ctx, u)
	if err != nil {
		return "", fmt.Errorf("failed to get connection capabilities: %w", err)
	}

	return string(data), nil
}

// SetDefaultConnection 设置默认连接
func (c *ConnectionClient) SetDefaultConnection(ctx context.Context, connectionID string) error {
	// 构建带查询参数的URL
	u := fmt.Sprintf("/api/v1/connection/set-default?connection=%s", url.QueryEscape(connectionID))

	_, err := c.client.Post(ctx, u, nil)
	if err != nil {
		return fmt.Errorf("failed to set default connection: %w", err)
	}
	return nil
}

// ReconnectConnection 重连连接
func (c *ConnectionClient) ReconnectConnection(ctx context.Context, connectionID string) error {
	// 构建带查询参数的URL
	u := fmt.Sprintf("/api/v1/connection/reconnect?connection=%s", url.QueryEscape(connectionID))

	_, err := c.client.Post(ctx, u, nil)
	if err != nil {
		return fmt.Errorf("failed to reconnect connection: %w", err)
	}
	return nil
}

// CloseConnection 关闭连接
func (c *ConnectionClient) CloseConnection(ctx context.Context, connectionID string) error {
	// 构建带查询参数的URL
	u := fmt.Sprintf("/api/v1/connection/close?connection=%s", url.QueryEscape(connectionID))

	_, err := c.client.Post(ctx, u, nil)
	if err != nil {
		return fmt.Errorf("failed to close connection: %w", err)
	}
	return nil
}

// ReconnectAll 重连所有连接
func (c *ConnectionClient) ReconnectAll(ctx context.Context) error {
	_, err := c.client.Post(ctx, "/api/v1/connections/reconnect-all", nil)
	if err != nil {
		return fmt.Errorf("failed to reconnect all connections: %w", err)
	}
	return nil
}

// HealthCheck 连接健康检查
func (c *ConnectionClient) HealthCheck(ctx context.Context, connectionID string) error {
	// 构建带查询参数的URL
	u := fmt.Sprintf("/api/v1/connection/health?connection=%s", url.QueryEscape(connectionID))

	_, err := c.client.Get(ctx, u)
	if err != nil {
		return fmt.Errorf("failed to check connection health: %w", err)
	}
	return nil
}
